package com.gitee.llj.shiro.controller;

import com.gitee.llj.tools.base.ResultModel;
import com.gitee.llj.tools.base.ResultStatus;
import com.gitee.llj.tools.exception.IncorrectCaptchaException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.xml.transform.Result;

/**
 * <p></p>
 *
 * @Author llj
 * @Date 2018/3/27
 */
@RestController
@RequestMapping("/api")
public class LoginController {
    /**
     * 用户登录
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/login")
    public ResultModel login(@RequestParam("username") String username,@RequestParam("password") String password){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            subject.login(token);
        } catch (IncorrectCredentialsException e) {
            return  new ResultModel(ResultStatus.FAIL.getSuccess(),"用户名或密码错误");
        } catch (LockedAccountException e) {
            return  new ResultModel(ResultStatus.FAIL.getSuccess(),"登录失败，该用户已被冻结");
        }catch (AuthenticationException e) {
            return  new ResultModel(ResultStatus.FAIL.getSuccess(),"用户名或密码错误");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultModel.ok(subject.getSession().getId());
    }

    /**
     * 未登录
     * @return
     */
    @RequestMapping("/unauth")
    public ResultModel unauth(){
        return new ResultModel(ResultStatus.FAIL.getSuccess(),"请先登录");
    }
    @RequestMapping("/")
    public ResultModel index(){return ResultModel.ok();}
}
